import React, { useState, useMemo } from 'react';
import { EditableProTable } from '@ant-design/pro-components';
import useDesignerStore from '@/store/Designer';
import { randomUUID } from '@/utils/dataflow';

function generateNewFieldName(existingNames) {
    const baseName = 'new_field';
    const fieldRegex = /^new_field(?:_(\d+))?$/;
    let maxNumber = 0;
    let baseExists = false;

    existingNames.forEach(name => {
        const match = name.match(fieldRegex);
        if (match) {
            if (match[1] === undefined) {
                baseExists = true;
            } else {
                const num = parseInt(match[1], 10);
                maxNumber = Math.max(maxNumber, num);
            }
        }
    });

    // 如果存在基础名称或已有带编号的字段，则增加编号
    if (baseExists || maxNumber > 0) {
        return `${baseName}_${maxNumber + 1}`;
    }
    return baseName; // 否则返回基础名称
}

export const UnionFieldResult = ({
    datasource,
    onChange,
    selectedRowKeys,
    onSelectionChange,
    columns
}) => {
    const { drawerHeight } = useDesignerStore()
    const editableKeys = datasource?.map((item) => item.columnId) ?? []

    return <EditableProTable
        columns={columns}
        scroll={{
            y: drawerHeight - 218,
            x: window.innerWidth - 100
        }}
        style={{
            width: 'calc(100% - 10px)'
        }}
        virtual
        rowSelection={{ selectedRowKeys, onChange: onSelectionChange, columnWidth: 50 }}
        rowKey='columnId'
        value={datasource}
        recordCreatorProps={{
            creatorButtonText: '添加字段',
            type: 'dashed',
            record: () => {
                const columnName = generateNewFieldName(datasource?.map(item => item.columnName) ?? []);
                return { columnId: randomUUID(), columnName, columnType: 'string', relations: [] }
            },
            newRecordType: 'dataSource',
        }}
        tableAlertRender={false}
        editable={{
            type: 'multiple',
            editableKeys,
            actionRender: (row, config, defaultDoms) => {
                return [defaultDoms.delete];
            },
            onValuesChange: (record, recordList) => {
                onChange?.(recordList);
            }
        }}
    />
}